import Vue from 'vue'
import login from '@/components/login'
import home from '@/components/home'
import register from '@/components/register'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'login'
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path:'/register',
    name:'register',
    component:register
  },
  {
    path:'/home',
    name:'home',
    component:home,
    redirect:'/home/user',
    meta:{
      requiresAuth:true
    },  
    //定义子界面
    children:[
      {
        path:'/home/user',
        component: (resolve) => require(['../views/user'], resolve)
      },
      {
        path:'/home/msgGet',
        component: (resolve) => require(['../views/messageGet'], resolve)
      },
      {
        path:'/home/msgGive',
        component: (resolve) => require(['../views/messageGive'], resolve)
      },
      {
        path:'/home/accessGet',
        component: (resolve) => require(['../views/accessGet'], resolve)
      },
      {
        path:'/home/accessGive',
        component: (resolve) => require(['../views/accessGive'], resolve)
      },
      {
        path:'/home/files',
        component: (resolve) => require(['../views/getfile'], resolve)
      },
      {
        path:'/home/myfiles',
        component: (resolve) => require(['../views/myfiles'], resolve)
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//过滤器，如果未登录，重定向到login界面
router.beforeEach((to,from,next)=>{
  let token = window.localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === null)) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else {
    next()
  }
})

export default router